import java.util.Random;

public class PhiEat_1 {

    public static void main(String[] args) {
        PhiPerson.chops = new Object[5];
        for (int i = 0; i < 5; i++) PhiPerson.chops[i] = 1;
        PhiPerson t1 = new PhiPerson(0);
        PhiPerson t2 = new PhiPerson(1);
        PhiPerson t3 = new PhiPerson(2);
        PhiPerson t4 = new PhiPerson(3);
        PhiPerson t5 = new PhiPerson(4);
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
        new Thread(t4).start();
        new Thread(t5).start();
    }
}

class PhiPerson implements Runnable {

    static Object[] chops;
    private int pos;
    public PhiPerson(int pos) {
        this.pos = pos;
    }


    @Override
    public void run() {
        while (true) {
            int left = (pos) % 5;
            int right = (pos + 1) % 5;
            synchronized (chops[left]) {
                if (chops[left].equals(1)) {
                    System.out.println("第" + (pos + 1) + "个哲学家拿了左手边的筷子");
                    chops[left] = 0;
                    synchronized (chops[right]) {
                        if (chops[right].equals(1)) {
                            System.out.println("第" + (pos + 1) + "个哲学家拿了右手边的筷子");
                            chops[right] = 0;
                            System.out.println("第" + (pos + 1) + "个哲学家正在eating");
                            System.out.println("第" + (pos + 1) + "个哲学家吃完了，把筷子放回了原处，开始thinking");
                            chops[right] = 1;
                        }
                    }
                    chops[left] = 1;
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
